package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(value = "/contractList" ,name = "分页查询已提交的购销合同列表数据")
    public String contractList(@RequestParam(value = "page",defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10")Integer pageSize){
//        查询本企业的购销合同 where company_id=??  and state =1  order by create_time desc
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId()).andStateEqualTo(1);
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo =  contractService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-contractList";
    }

    @RequestMapping(value = "/list" ,name = "分页查询报运单列表数据")
    public String list(@RequestParam(value = "page",defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10")Integer pageSize){
//        查询本企业的购销合同 where company_id=??  and state =1  order by create_time desc
        ExportExample example = new ExportExample();
        ExportExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo =  exportService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-list";
    }

    @RequestMapping(value = "/toExport" ,name = "进入到新增报运单页面")
    public String toExport(String id){ // 可以用数组接收 也可以用list接收，也可以直接用字符串接收。这里我直接使用字符串接收“111,33333”
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    @RequestMapping(value = "/edit",name = "保存报运单信息")
    public String edit(Export export){

        if(StringUtils.isNotEmpty(export.getId())){
//           id不为空，应该执行修改方法
            exportService.update(export);
        }else{
            export.setId(UUID.randomUUID().toString());
            export.setCompanyId(getCompanyId());
            export.setCompanyName(getCompanyName());
            export.setState(0);
            export.setCreateTime(new Date()); //创建时间 ,为了方便排序
            export.setCreateBy(getUser().getId()); //创建人id
            export.setCreateDept(getUser().getDeptId());// 创建人部门id
            exportService.save(export);
        }
        return "redirect:/cargo/export/list.do"; // 重定向到列表页面
    }
    @RequestMapping(value = "/toUpdate" ,name = "进入到编辑报运单页面")
    public String toUpdate(String id){
//        当前报运单
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
//        当前报运单下货物数据
       List<ExportProduct> exportProductList = exportProductService.findListByExportId(id);
        request.setAttribute("eps",exportProductList);

        return "cargo/export/export-update";
    }

    @RequestMapping(value = "/exportE" ,name = "海关电子报运")
    public String exportE(String id){
        Export export = exportService.findById(id);
        ExportVo exportVo = new ExportVo(); //包含报运单和报运单下货物
        BeanUtils.copyProperties(export,exportVo); //还需要手动设置的属性是：exportId  products
        exportVo.setExportId(id);

//        查询当前报运单下的货物
        List<ExportProduct> exportProductList = exportProductService.findListByExportId(id);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo); // 需要手动个Vo设置的是：eid 、exportProductId
            exportProductVo.setEid(id);
            exportProductVo.setExportProductId(exportProduct.getId());

            exportVo.getProducts().add(exportProductVo);
        }

        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);
        export.setState(5); // 表示已报运但是还没有返回报运的结果 状态值暂时设置成5
        exportService.update(export);



////        从海关项目中获取结果
//        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);
//        exportService.updateE(exportResult);



        return "redirect:/cargo/export/list.do";
    }

    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/exportPdf" ,name = "导出报运单PDF")
//    @ResponseBody
    public void exportPdf(String id) throws Exception{
        //        1、读取模板
        String templatePath = session.getServletContext().getRealPath("/make/pdfprint/export.jasper");
        FileInputStream inputStream = new FileInputStream(templatePath);
//        当前报运单
        Export export = exportService.findById(id);
        Map<String, Object> parameters = BeanMapUtils.beanToMap(export);

//        当前报运单下货物数据
        List<ExportProduct> exportProductList = exportProductService.findListByExportId(id);
        JRDataSource dataSource =  new JRBeanCollectionDataSource(exportProductList);
        //        3、数据填充
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters,dataSource );// Connection意味着数据是从数据库中直接获取的  DataSource意味着这个数据是需要封装后

        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byteArrayOutputStream.write(bytes);

//        ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName
        downloadUtil.download(byteArrayOutputStream,response,"报运单.pdf");
    }

}
